package com.example.batch.writer;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.batch.item.file.FlatFileFooterCallback;
import org.springframework.batch.item.file.FlatFileHeaderCallback;
import org.springframework.batch.item.file.FlatFileItemWriter;
import org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor;
import org.springframework.batch.item.file.transform.DelimitedLineAggregator;
import org.springframework.core.io.PathResource;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Writer;
import java.util.Date;
import java.util.List;

/**
 * @author LiYuhang
 * @version 0.1
 * @application Flat文件格式写入类
 * @Date 2021/7/12 09:35
 */
@Component
@Slf4j
public class MyFlatFileItemWriter<T> extends FlatFileItemWriter {
    public static final String filaPath = "/Users/yuhang/Downloads/ids-result.txt";

    @Override
    public String doWrite(List items) {
        log.info("size:{}",items.size());
        return super.doWrite(items);
    }

    public MyFlatFileItemWriter() {
        repayOfDelimitedLine();
    }

    private void repayOfDelimitedLine() {
        setResource(new PathResource(filaPath));
        setAppendAllowed(true); //
        setLineAggregator(new DelimitedLineAggregator<T>() {{
            setDelimiter("");
            setFieldExtractor(new BeanWrapperFieldExtractor<T>() {{
                setNames(new String[]{"id"});
            }});
        }});

        /**
         * 写文件头
         */
        setHeaderCallback(new FlatFileHeaderCallback() {
            @Override
            public void writeHeader(Writer writer) throws IOException {
                writer.write("#begin time: " + DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
            }
        });

        /**
         * 写文件尾
         */
        setFooterCallback(new FlatFileFooterCallback() {
            @Override
            public void writeFooter(Writer writer) throws IOException {
                writer.write("#end time: " + DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
            }
        });
    }



}
